<?php
/*
 * PHP Image Upload Class
 *
 * Simply setup the class and then call  save()
 *   $uploader = new ImageUpload($source);
 *   $source : fieldname in html form
 *              or url
 *
 * To process upload and save to file
 *   echo $uploader->save();
 *
 */
#error_reporting(0);
 
require_once('FileUpload.php');
require_once('UploadPath.php');

require_once('Debug.lib.php');

require_once('Imaging.php');
require_once('Imaging/ResizeMode0.php');
require_once('Imaging/ResizeMode1.php');
require_once('Imaging/ResizeMode2.php');
require_once('Imaging/ResizeMode3.php');
require_once('Imaging/ResizeMode4.php');
require_once('Imaging/ResizeMode6.php');
require_once('Imaging/ResizeMode7.php');


class ImageUpload  Extends FileUpload{
  private $source_temp_path = ''; # source image temp file
  private $default_bgcolor  = '#FFFFFF';
  private $default_zoom     = 100;
  private $default_x_crop   = 100;
  private $default_y_crop   = 100;

#  function __construct($fieldname_or_url, $allowed_type,$maxSize = 512000){
#    parent::__construct($fieldname_or_url, $allowed_type,$maxSize);
#  }

   function __destruct() {
     //fclose($this->full_path); # remove file created by tmpfile
     if (file_exists($this->full_path)){
       unlink($this->full_path);
     }
   }

  /* Upload the image using FileUpload code and put more imaging add-on in this class
   * 
   */
  private function create_temp_source(){
    //$temp_file = tempnam('/home/cms/temp/', 'imageupload');
    //$temp_file = tmpfile();
    $temp_file = tempnam("/tmp", "ImageUpload");
    $this->full_path = $temp_file;
    #error_log("Writing to path: $full_path\n");
    $type = $this->type;
    if ($type == 'http_post'){
      list($flag, $msg) = $this->process_uploaded_file();
      $this->debug($type.' - '.$flag.' - '.$msg);
    } elseif ($type == 'copy_from_url'){
      list($flag, $msg) = $this->save_from_url();
      $this->debug($type.' - '.$flag.' - '.$msg);
    } elseif ($type == 'local_file'){
      list($flag, $msg) = $this->copy_local_file();
      $this->debug($type.' - '.$flag.' - '.$msg);
    } else {
    	$flag = 15;
    	$msg  = 'invalid upload method';
    }
    
    $this->debug("created temp image source file on ".$temp_file);
    $this->source_temp_path = $temp_file;
    return array($flag, $msg);
  }




  /*
   * @param: $base_path: base folder for saving the image
   *         as it will save multiple copy of image, full path is not supported.
   * @param: $a_image_setting: setting of each image
   *   three examples:
   *	 0=>array( 'convert_to'=>'','mode'=>0,'filename'=>get_upolad_image_path($id,0,array( 'path_by_date'=>1 , 'path_by_id'=>8,'default_filename'=>'', 'append_updatetime'=>'1' )) ),
	 *   1=>array( 'convert_to'=>'jpg,png','max_dim' => '100x100','mode'=>1,'filename'=>get_upolad_image_path($id,1,array( 'path_by_date'=>1 , 'path_by_id'=>8,'default_filename'=>'', 'append_updatetime'=>'1' )) ),
   *   2=>array( 'convert_to'=>'jpg,png','max_dim' => '','mode'=>1,'filename'=>get_upolad_image_path($id,2,array( 'path_by_date'=>1 , 'path_by_id'=>8,'default_filename'=>'', 'append_updatetime'=>'1' )) ),
   *
   *  
   *
   * The output path will like
   *   $base_path $gen_path  /0/originalimage
   *   $base_path $gen_path  /1/thumbnail
   *   $base_path $gen_path  /2/mediumsized
   * where 
   *   $gen_path function gen by image_sequence, id, or date/time
   *
   *
   */
  function save($base_path, $a_image_setting=array()){
    if ($this->invalid_source==1 || empty_string($this->type) ){
    	#echo "ImageUpload: Invalid Source.\n";
		  return array(10, 'ImageUpload: Invalid Source.');
	  }
    list($flag, $msg) = $this->create_temp_source();
    if ($flag != 0){
    	return array($flag, $msg);
    }
    
    #$base_path = rtrim($base_path, '\/\\'); # remove trailing slash
    if (substr($base_path, -1) != '/') $base_path .= '/';              # add trailing slash

    $this->debug("ImageUpload - saving to base path: $base_path\n");
    list($w, $h, $type) = getimagesize($this->source_temp_path); # get original image size
    $this->debug("Source: W:$w, H:$h, Type:$type\n");

    $a_processed_image = array(); # array of process image
    foreach ($a_image_setting as $image_count => $h_image){ # changed from aoa(perl) to aoh(php), so use hash to access
      
      $max_dim = get_hash_param($h_image, 'max_dim', '0x0'); #remove support the 4th param , 'image_dim'
      #echo("$image_count MAX DIM:  $max_dim");
      #isset($h_image['max_dim']) && !empty_string($h_image['max_dim']) ? $h_image['max_dim'] : '0x0';
      
      $this->debug(" Image Count $image_count");
      $this->debug(" Size:    ".$max_dim);
      $this->debug(" Convert: ".$h_image['convert_to']);      
      $this->debug(" Mode:    ".$h_image['mode']);
      
      
      $force_convert = 0;  # force convert is enable if image format is different, even though the size not need to convert.
      $convert_to    = get_hash_param($h_image, 'convert_to', '', 'string');
      $ext = $this->get_extension(); # original image extension, for final ext

       if ($convert_to != ''){ # has specified what to convert to
        $a_convert_to   = explode(',', $convert_to);
        if (! in_array($ext, $a_convert_to) ){ # current uploaded extension is not in allowed conversion format
          $ext = $a_convert_to[0];
          $force_convert = 1;
		      $this->debug("  Force Convert to: $ext");
        }
      } 
      $this->debug(" Image ext: ".$ext);
      # end handling output format
      
      $relative_path  = $h_image['filename'].'.'.$ext;

      $this->debug(" Saving image to $relative_path\n");

//      #} elseif ($localize == 2){ # localize or not
      $mode = get_hash_param($h_image, 'mode', 1, 'int');

      $full_path = $base_path.$relative_path; // with filename
      $dirname   = dirname($full_path);
      $this->debug("  Create dir: $dirname");
      if (!file_exists($dirname)){
        mkdir($dirname, 0775, true);  # recursive create directory
      }
      list($max_w, $max_h) = explode('x', $max_dim);
      $mode = $h_image['mode'];
      unset($h_image['mode']);
      unset($h_image['max_dim']);
      unset($h_image['convert_to']);
      
      if ($mode > 0 && $max_dim == '0x0'){ # all image dim must be sepecified except mode 0 
      	array_push($a_processed_image, array($image_count, '0x0', '', ''));
      	continue;
      }
      
      switch ($mode){
        case 0: # direct copy mode
          $uploader = new Imaging_ResizeMode0($this->source_temp_path);
          break;
        case 1:
          $uploader = new Imaging_ResizeMode1($this->source_temp_path);
          break;
        case 2:
          $uploader = new Imaging_ResizeMode2($this->source_temp_path);
          break;
        case 3:
          $uploader = new Imaging_ResizeMode3($this->source_temp_path, $h_image);
          break;
        case 4:
          $uploader = new Imaging_ResizeMode4($this->source_temp_path, $h_image);
          break;
        case 6:
          $uploader = new Imaging_ResizeMode6($this->source_temp_path, $h_image);
          break;
        case 7:
          $uploader = new Imaging_ResizeMode7($this->source_temp_path, $h_image);
          break;
        default:
          $uploader = '';
          $this->debug('invalid image resize mode');
      }

      $image_size = $uploader->resize($max_w, $max_h);
      $image_param = $uploader->save($full_path, $ext);
      
      array_push($a_processed_image, array($image_count, $image_size, $relative_path, $image_param));
      $this->debug(" try to save to path $full_path\n");
    
      # any error?
      if ($image_count > 0 && $this->is_image_smaller($w, $h, $image_size)){
      	# ??? bugme: to be fixed
        break;
      }

    } // end foreach ($a_image_setting

    $this->debug("Delete temp ".$this->source_temp_path);
    //unlink($this->source_temp_path);
    //fclose($this->source_temp_path); // use fclose as created by tmpfile() function, moved to __destruct
    return array(0, $a_processed_image);
  }



  #
  function is_image_smaller($w, $h, $image_size){
    $this->debug('is_image_smaller is not implemented ');
    return 0;
  }




}// end ImageUpload class


?>